﻿using System;
using System.Windows.Forms;
using NDK.Module.BLL;
using Tool;

namespace NDK.Frm
{
    static class Program
    {

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        [SysInit.Interceptor]

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            System.Threading.Mutex mutex = new System.Threading.Mutex(false, "ThisShouldOnlyRunOnce");
            bool running = true;
            try
            {
                running = !mutex.WaitOne(0, false);
            }
            catch { }

            //此处首先读取一次配置，因为程序启动时就需要知道当前语言选择，用于下面的提示信息的语言类型
            Ini ini = new Ini(Application.StartupPath + @"\Config\Configuration.ini");
            string language = ini.IniReadConfig("Language");
            if (language != string.Empty)
                Configuration.language = (Configuration.Language)Enum.Parse(typeof(Configuration.Language), language);

            if (running)
            {
                DialogResult result = MessageBox.Show(Configuration.language == Configuration.Language.English ? "An instance has already been run (or the old instance has not been completely closed). Do you want to open another instance?" : "已经运行了一个实例（或旧实例尚未完全关闭），是否再开启一个实例？", Configuration.language == Configuration.Language.English ? "Tip" : "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                    SysInit.Init();
            }
            else
            {
                //if (!HslCommunication.Authorization.SetAuthorizationCode("BB1F254923E056E538F969D9546DEFA5"))
                //{
                //    MessageBox.Show("激活失败！");
                //    return;
                //}

                //MessageBox.Show("激活成功！");
                SysInit.Init();
            }

        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.StackTrace);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show($"{e.IsTerminating},{e.ToString()}");
        }
    }
}
